import {setStorage, getStorage, removeStorage} from "@/util/auth";
import {getUser, loginApi} from "@/api/user";
import {getSign} from "@/api/im";
import Vue from "vue";
const state={
    token: getStorage('token'),
    user:getStorage('user'),
    identity:getStorage('identity'),
    IMReady: false,
	userSig:'',
	sdkAppID:'',
	userID:''
}
const mutations={
    SET_USER_SIG(state,sig){
        state.userSig=sig;
    },
	SET_SDK_APP_ID(state,id){
        state.sdkAppID=id;
    },
	SET_USER_ID(state,id){
        state.userID=id;
    },
	SET_TOKEN(state,token){
        if(token===null){
            removeStorage('token');
        }else{
            setStorage('token',token)
        }
        state.token=token;
    },
    SET_USER(state,user){
        if(user===null){
            removeStorage('user');
        }else{
            setStorage('user',user)
        }
        state.user=user
    },
    SET_IDENTITY(state,identity){
        setStorage('identity',identity)
        state.identity=identity
    },
    SET_READY: (state, ready) => {
        state.IMReady = ready
    },
}
const actions={
    login({commit}, form) {
        return new Promise((resolve, reject) => {
            loginApi(form).then((res)=>{
                commit('SET_TOKEN',res.token);
                commit('SET_USER',res.user);
                commit('SET_IDENTITY',form.type);
                resolve();
            }).catch(()=>{
                reject();
            })
        })
    },
    getUser({commit}){
        return new Promise((resolve, reject) => {
            getUser({type:getStorage('identity')}).then((res)=>{
                commit('SET_USER',res);
				uni.$TUIKit.updateMyProfile({
				    nick: res.realName, avatar: res.faceUrl
				})
                resolve(res);
            }).catch(()=>{
                reject();
            })
        })
    },
    loginIM({commit}){
        return new Promise((resolve, reject)=>{
            const user=state.user;
            const identity=state.identity;
            const prefix=identity==1?'dhs_personal':'dhs_enterprise';
            const userId=prefix+'_'+user.mobile;
            let userName = user.realName
            getSign({userId:userId}).then((res)=>{
                const userSig=res.userSig;
                uni.$TUIKit.login({userID:userId,userSig}).then(()=>{
					commit('SET_USER_SIG',userSig);
					commit('SET_USER_ID',userId);
                    resolve('登录成功');
                }).catch(()=>{
                    reject('IM登录失败');
                })
            }).catch(()=>{
                reject('IM登录失败');
            })
        })
    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}
